package com.flh.crm.settings.web.controller;

import com.flh.crm.settings.domain.User;
import com.flh.crm.settings.service.UserService;
import com.flh.crm.settings.service.impl.UserServiceImpl;
import com.flh.crm.utils.MD5Util;
import com.flh.crm.utils.PrintJson;
import com.flh.crm.utils.ServiceFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class UserController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println("进入到用户控制器");
        String path = request.getServletPath();
        if ("/settings/user/login.do".equals(path)){
            login(request,response);

        }else if ("/settings/user/xxx.do".equals(path)){

        }


    }
    private void login(HttpServletRequest request, HttpServletResponse response)  {

    System.out.println("进入到验证登录的操作");

    String loginAct = request.getParameter("loginAct");
    String loginPwd = request.getParameter("loginPwd");
    //将密码的明文形式转化为MD5的形式

        loginPwd = MD5Util.getMD5(loginPwd);

        //接收浏览器ip
        String ip = request.getRemoteAddr();
        System.out.println("-------IP"+ip);

        //业务层开发，统一使用代理类的接口对象
        UserService us= (UserService) ServiceFactory.getService(new UserServiceImpl());

        try {
            User user= us.login(loginAct,loginPwd,ip);
            request.getSession().setAttribute("user",user);

            //如果程序执行到此处，说明业务层没有为·controller抛出异常
            //表示登录成功
            /*
            * {"success":true}
            * */
            //转为键值对发送到前台

            PrintJson.printJsonFlag(response,true);

        }catch (Exception e){
         e.printStackTrace();

         //抛出异常登录失败
            /*
            {"success":true,
            "msg":?
            }

            * */
          String msg = e.getMessage();
          //作为控制器controller,需要为ajax请求提供多项信息
            /*
            *
            * 有两种手段
            * 1.打包成map ->json
            * 2.创建一个Vo
            *   private boolean success ;
            *   private String msg;
            * 注：Vo一般返回大量信息使用 一般使用map就ok了
          *
            *
            * */

            Map<String ,Object> map = new HashMap<String, Object>();
            map.put("success",false);
            map.put("msg",msg);
            PrintJson.printJsonObj(response,map);





        }


    }


}












